package org.example.oop.thread;

import lombok.SneakyThrows;

/**
 * org.example.oop.thread
 *
 * @author moLei
 * @description 生产者, 消费者线程
 * @date 2025/6/22
 */
public class ConsumerProducerThreadDemo {

    private static Object lock = new Object();

    private static int foodFlag = 0;

    public static void main(String[] args) {

        for (int i = 0; i < 5; i++) {
            new Thread(new Runnable() {
                @Override
                @SneakyThrows
                public void run() {
                    while (true) {
                        synchronized (lock) {
                            producerFun();
                        }
                    }
                }
            }, "生产者线程"+i).start();
        }


        for (int i = 0; i < 2; i++) {
            new Thread(new Runnable() {
                @Override
                @SneakyThrows
                public void run() {
                    while (true) {
                        synchronized (lock) {
                            consumer();
                        }
                    }
                }
            }, "消费者线程"+i).start();
        }
}

    private static void consumer() throws InterruptedException {
        if (foodFlag == 0) {
            // 没有食物，唤醒生产者线程
            lock.notifyAll();
            // 自身陷入等待状态
            lock.wait();
        } else {
            System.out.println(Thread.currentThread().getName() + "消费者食物,剩余食物: " + foodFlag--);
        }
    }

    private static void producerFun() throws InterruptedException {
        if (foodFlag != 0) {
            // 有食物,生产完毕,唤醒消费者
            lock.notifyAll();
            // 自己进入等待
            lock.wait();
        } else {
            // 没有食物,生产食物
            foodFlag += 100;
            System.out.println(Thread.currentThread().getName() + "生产者生产食物，剩余食物：" + foodFlag);
        }
    }
}
